import { createTransport } from 'nodemailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';
import { BUSINESS_ERROR_CODE } from 'src/common/exceptions/business.error.codes';
import { BusinessException } from 'src/common/exceptions/business.exception';
import { EMAIL } from 'src/config';
const codes = new Map();

export class Email {
  private transporter = createTransport({
    host: EMAIL.host,
    port: EMAIL.port,
    secure: EMAIL.secure,
    auth: {
      user: EMAIL.user,
      pass: EMAIL.pass,
    },
  });

  // 发送验证码的方法
  send({ email, subject = '卡包管理系统', html = '' }) {
    const code = Number(Math.random().toString().slice(-6));
    const options = {
      from: `${EMAIL.alias}<${EMAIL.user}>`,
      to: email,
      subject,
      text: `验证码为${code},请勿泄露`,
      html,
    };
    codes.delete(email);
    codes.set(email, code);
    return new Promise<SMTPTransport.SentMessageInfo>((resolve, reject) => {
      this.transporter.sendMail(options, (error, info) => {
        if (error) {
          reject(error);
        } else {
          resolve(info);
        }
      });
    });
  }
  // 校验方法
  static validate(email: string, userCode: number) {
    const code = codes.get(email);
    // 测试验证码
    if (userCode === 123456) {
      return true;
    }
    if (!code) {
      throw new BusinessException({
        code: BUSINESS_ERROR_CODE.COMMON,
        message: '无法获取验证码，请首先发送验证码！',
      });
    }
    if (code !== userCode) {
      throw new BusinessException({
        code: BUSINESS_ERROR_CODE.COMMON,
        message: '验证码错误',
      });
    }
    // 清除验证码，防止重复使用
    codes.delete(email);
    return true;
  }
}
